import React from 'react';
import {FlatList, Image, StyleSheet, Text} from 'react-native';
import {TouchableOpacity, View, Button} from 'react-native-ui-lib';
import {commonStyles} from '../../configs/commonStyle';
import BasePage from '../BasePage';
import ListEmpty from '../common/ListEmpty';
import ListFooter from "../common/ListFooter";
import DateFilter from '../components/DateFilter';
import {inject, observer} from 'mobx-react';
import moment from 'moment';
import AbnormalDialog from './components/AbnormalDialog';
import {listUnusuals} from '../../net/transfer';
import {IconImage} from '../../utils';
import {
  logger,
  setClipboardContent,
} from "../../utils/util";
const statusLabelMap = {
  1: '待审核',
  2: '已驳回',
  3: '已通过',
};
const statusStyleMap = {
  1: commonStyles.text_gray_13,
  2: commonStyles.text_red_13,
  3: commonStyles.text_green_13,
};

/**
 * 中转记录
 */
@inject('userStore', 'appStore')
@observer
export default class TransferAbnormal extends BasePage {
  constructor(props) {
    super(props);
    this.isLoading = false;
    this.pageNo = 1;
    this.totalPages = 1;
    this.state = {
      isRefreshing: false,
      showEmpty: false,
      showFoot: 0,
      dataList: [],
      timeStart: moment().format('YYYY-MM-DD'),
      timeEnd: moment().format('YYYY-MM-DD'),
    };
  }

  componentDidMount() {
    this.loadData();
  }

  loadData() {
    this.getListUnusuals();
  }

  getListUnusuals = () => {
    const {dataList, timeStart, timeEnd} = this.state;
    this.isLoading = true;
    listUnusuals({
      timeStart: `${timeStart} 00:00:00`,
      timeEnd: `${timeEnd} 23:59:59`,
      showLoading: true,
      page: this.pageNo,
      size: 10,
    })
      .then(res => {
        logger(res.result);
        let tempArr = [];
        let showf;
        this.totalPages = res?.result.totalPages;
        if (this.pageNo == 1) {
          tempArr = res?.result.content || [];
          showf = 0;
        } else {
          tempArr = dataList.concat(res?.result.content);
          showf = (this.pageNo > this.totalPages) ? 1 : 0;
        }
        this.setState({
          //复制数据源
          dataList: tempArr,
          showFoot: showf,
          isRefreshing: false,
          showEmpty: (this.pageNo == 1 && tempArr.length == 0 ? true : false),
        });
      })
      .finally(() => {
        this.isLoading = false;
      });
  };

  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.pageNo = 1;
      this.loadData();
    }
  };

  _onEndReached = async () => {
    logger('_onEndReached')
    //如果是正在加载中或到底了，则返回
    if (this.state.showFoot != 0) {
      return;
    }
    //如果当前页大于或等于总页数，那就是到最后一页了，返回
    if (this.pageNo > this.totalPages || this.totalPages == 0) {
      return;
    } else {
      this.pageNo++;
    }
    //底部显示正在加载更多数据
    this.setState({ showFoot: 2 });
    //获取数据
    this.loadData();
  };

  render_goods_item = cake => {
    return (
      <View row marginT-10 centerV>
        <Image
          source={
            cake?.status == 2 ? IconImage.ic_unchecked : IconImage.ic_checked
          }
          style={{width: 17, height: 17, marginRight: 5}}
        />
        <View flex>
          <Text style={commonStyles.text_black_13}>
            {cake?.goodsName}（{cake?.xmbzNo}）
          </Text>
        </View>

        <Button
          style={{width: 100}}
          color="#333"
          size="xsmall"
          label="提交异常"
          onPress={() => this.abnormalDialog.show({cake})}
        />
      </View>
    );
  };

  render_item = ({item, index}) => {
    return (
      <View>
        <View style={styles.titleWrap}>
          <TouchableOpacity flex activeOpacity={1} onPress={() => setClipboardContent(item?.xmbzNo)}>
            <Text style={commonStyles.text_black_14}>{item.goodsName}（单号：{item?.xmbzNo}）</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>状态</Text>
            <Text style={statusStyleMap[item?.status]}>
              {statusLabelMap[item?.status]}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>审核人</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.operator}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>审核意见</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.processingResults}
            </Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>异常内容</Text>
            <Text style={commonStyles.text_black_13}>
              {item?.abnormalContent}
            </Text>
          </View>
          {item.transferCakeInfos?.length ? (
            <View>
              {item.transferCakeInfos.map(cake => {
                return this.render_goods_item(cake);
              })}
            </View>
          ) : null}
        </View>
      </View>
    );
  };

  render() {
    const {dataList, isRefreshing, showFoot} = this.state;
    return (
      <View
        useSafeArea
        style={{...commonStyles.body_primary, marginBottom: 32}}>
        <View style={commonStyles.container}>
          <View row centerV>
            <DateFilter
              onQueryClick={(timeStart, timeEnd) =>
                this.setState(
                  {
                    timeStart,
                    timeEnd,
                  },
                  () => this._renderRefresh(false),
                )
              }
            />
            <TouchableOpacity
              activeOpacity={1}
              throttleTime={1000}
              style={styles.btn}
              onPress={() => this._renderRefresh(false)}>
              <Text style={commonStyles.text_black}>刷新</Text>
            </TouchableOpacity>
          </View>
          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{flexGrow: 1}}
            keyExtractor={(item, index) => 'menu_' + index}
            renderItem={this.render_item}
            ListEmptyComponent={() => (
              <ListEmpty showEmpty={this.state.showEmpty} />
            )}
            onEndReached={this._onEndReached}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => <ListFooter showFoot={this.state.showFoot} page={this.pageNo} />}
          />
        </View>

        <AbnormalDialog ref={r => (this.abnormalDialog = r)}></AbnormalDialog>
      </View>
      // <View></View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: '#F9D63B',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: 'white',
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 6,
  },
  line: {
    height: 1,
    backgroundColor: '#EFEFEF',
    marginHorizontal: 15,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: '#F9D63B',
    borderRadius: 5,
  },
});
